import 'dart:async';
import 'dart:io';

import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:lcapp/api/interface/user_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/basic/user_info.dart';
import 'package:lcapp/config/const_config.dart';
import 'package:lcapp/data/vip_type_data_entity.dart';
import 'package:lcapp/model/db/apple_pay_operate.dart';
import 'package:lcapp/model/event/event_bus.dart';
import 'package:lcapp/model/param/base_param.dart';
import 'package:lcapp/model/pay/in_app_pay.dart';
import 'package:lcapp/model/toast/toast.dart';
import 'package:lcapp/page/min/choose_payment_page.dart';
import 'package:lcapp/widget/asr_app_bar.dart';
import 'package:lcapp/widget/asr_cache_image.dart';

class MinVipPage extends StatefulWidget {
  const MinVipPage({Key? key}) : super(key: key);

  @override
  _MinVipPageState createState() => _MinVipPageState();
}

class _MinVipPageState extends State<MinVipPage> {

  late int vipType;
  late StreamSubscription _subscription;
  List<VipTypeDataEntity> vips=[VipTypeDataEntity(),VipTypeDataEntity()];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    refreshUserInfo(refreshBlock: (){setState(() {});});
    /// 监听支付状态
    _subscription = eventBus.on<PayState>().listen((event) {
      if (event.state == 0) {
        Navigator.of(context).pushNamed('MinOpenVipSuccessPage').then((value){
          refreshUserInfo(refreshBlock: (){
            if(mounted){setState(() {
            });}
          });
        });
      }
    });
    getVipList();
  }

  getVipList()async{
    ResponseData res = await UserAPI.getVipList();
    if(res.code==200){
      List arr = res.data??[];
      vips.clear();
      for (var element in arr) {
        VipTypeDataEntity entity = VipTypeDataEntity().fromJson(element);
        vips.add(entity);
      }
      if(mounted){setState(() {
        if(vips.isNotEmpty){
          vipType = vips[0].id!;
        }
      });}
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _subscription.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AsrAppBar(
        titleText: '会员中心',
        elevation: 0.3,
        backgroundColor: Color(0xffF9DDB1),
      ),
      body: Container(
        width: 1.sw,
        height: 1.sh,
        color: Color(0xffF0B979),
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 30.w,vertical: 50.w),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xffF9DDB1),Color(0xffF0B979),],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter
                  )
                ),
                child: Row(
                  children: [
                    ClipRRect(
                      child: ASRCacheImage(image: userInfo.img??'assets/icon/p_head.png',width: 90.w,height: 90.w,fit: BoxFit.fitWidth,),
                      borderRadius: BorderRadius.circular(10.w),
                    ),
                    Expanded(child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 30.w),
                      child: Column(
                      children: [
                        Container(
                          child: Row(
                            children: [
                              Text('${userInfo.name}',style: TextStyle(
                                  color: Color(0xff472C2F),
                                  fontSize: 40.sp,
                                  fontWeight: FontWeight.w600
                              ),),
                            ],
                          ),
                        ),
                        SizedBox(height: 10.w,),
                        Visibility(child: Container(
                          child: Row(
                            children: [
                              Image.asset('assets/min/min_vip.png',height: 30.w,),
                            ],
                          ),
                        ),visible: userInfo.vip==1,)
                      ],
                    ),)),
                    Visibility(child: Text(formatDate(DateTime.fromMillisecondsSinceEpoch(userInfo.vipEnd!),[yyyy,'-',mm,'-',dd])+' 到期',style: TextStyle(
                      color: Color(0xff7F5026),
                      fontSize: 26.sp,
                      fontWeight: FontWeight.w500
                    ),),visible: userInfo.vip==1&&userInfo.vipEnd!=null&&userInfo.vipEnd!=0,),
                  ],
                ),
              ),
              Container(
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        colors: [Color(0xff383F59),Color(0xff191E33)],
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter
                    ),
                    borderRadius: BorderRadius.circular(40.w)
                ),
                child: Column(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal:30.w,vertical: 50.w),
                      child:Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Row(
                            children: [
                              GestureDetector(
                                onTap: (){
                                  setState(() {
                                    vipType=vips[0].id!;
                                  });
                                },
                                child: Stack(
                                  children: [
                                    Container(
                                      width: (1.sw-60.w-11.w)*0.5,
                                      height: vipType==vips[0].id? 230.w:220.w,
                                      decoration: BoxDecoration(
                                          gradient: vipType==vips[0].id?LinearGradient(
                                              colors: [Color(0xffF1BF83),Color(0xffF9DEB0)],
                                              begin: Alignment.topCenter,
                                              end: Alignment.bottomCenter
                                          ):LinearGradient(
                                              colors: [Color(0xff494E64),Color(0xff5F6A88)],
                                              begin: Alignment.topCenter,
                                              end: Alignment.bottomCenter
                                          ),
                                          borderRadius: BorderRadius.circular(10.w)
                                      ),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.start,
                                        children: [
                                          vipType==vips[0].id&&userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'?Row(
                                            children: [
                                              Image.asset('assets/min/min_djq.png',width: 200.w,)
                                            ],
                                          ):Container(height: 30.w,),
                                          Text('vip年卡(1年)',style: TextStyle(
                                              color:vipType==vips[0].id? Color(0xff7B5228):Color(0xffFFD496),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 28.sp
                                          ),),
                                          SizedBox(height: 15.w,),
                                          Text(BaseParam.isCheck?'购年卡':'￥${vips[0].priceCurrent}',style: TextStyle(
                                              color: vipType==vips[0].id?Color(0xff7B5228):Color(0xffFFC36F),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 40.sp
                                          ),),
                                          SizedBox(height: 15.w,),
                                          Text(BaseParam.isCheck?'尊享年卡权益':'原价￥${vips[0].priceOriginal}',style: TextStyle(
                                              color:vipType==vips[0].id? Color(0xff7B5228):Color(0xffFFD496),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 28.sp
                                          ),),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              SizedBox(width: 11.w,),
                              GestureDetector(
                                onTap: (){
                                  setState(() {
                                    vipType=vips[1].id!;
                                  });
                                },
                                child: Stack(
                                  children: [
                                    Container(
                                      width: (1.sw-60.w-11.w)*0.5,
                                      height: vipType==vips[1].id? 230.w:220.w,
                                      decoration: BoxDecoration(
                                          gradient: vipType==vips[1].id?LinearGradient(
                                              colors: [Color(0xffF1BF83),Color(0xffF9DEB0)],
                                              begin: Alignment.topCenter,
                                              end: Alignment.bottomCenter
                                          ):LinearGradient(
                                              colors: [Color(0xff494E64),Color(0xff5F6A88)],
                                              begin: Alignment.topCenter,
                                              end: Alignment.bottomCenter
                                          ),
                                          borderRadius: BorderRadius.circular(10.w)
                                      ),
                                      child: Column(
                                        mainAxisAlignment: MainAxisAlignment.start,
                                        children: [
                                          vipType==vips[1].id&&userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'?Row(
                                            children: [
                                              Image.asset('assets/min/min_djq.png',width: 200.w,)
                                            ],
                                          ):Container(height: 30.w,),
                                          Text('vip年卡(2年)',style: TextStyle(
                                              color:vipType==vips[1].id? Color(0xff7B5228):Color(0xffFFD496),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 28.sp
                                          ),),
                                          SizedBox(height: 15.w,),
                                          Text(BaseParam.isCheck?'购年卡':'￥${vips[1].priceCurrent}',style: TextStyle(
                                              color: vipType==vips[1].id?Color(0xff7B5228):Color(0xffFFC36F),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 40.sp
                                          ),),
                                          SizedBox(height: 15.w,),
                                          Text(BaseParam.isCheck?'尊享年卡权益':'原价￥${vips[1].priceOriginal}',style: TextStyle(
                                              color:vipType==vips[1].id? Color(0xff7B5228):Color(0xffFFD496),
                                              fontWeight: FontWeight.w600,
                                              fontSize: 28.sp
                                          ),),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                            crossAxisAlignment: CrossAxisAlignment.end,
                          ),
                          GestureDetector(
                            onTap: ()async{
                              if(userInfo.vip==1){
                                showToast('当前已是会员身份');
                                return;
                              }

                              double? money;
                              if(vipType==vips[0].id){
                                money = vips[0].priceCurrent;
                                if(userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'){
                                  money = vips[0].priceReduced;
                                }
                              }else{
                                money=vips[1].priceCurrent;
                                if(userInfo.inviter!=null&&userInfo.inviter!=userInfo.invite&&userInfo.invite!='0'){
                                  money = vips[1].priceReduced;
                                }
                              }
                              if(BaseParam.isCheck){
                                showLoading();
                                ResponseData res = await UserAPI.applePay(vipType);
                                hideLoading();
                                if(res.code==200){
                                    Map<String, dynamic> map = {
                                      'orderId': res.data['orderId'],
                                      'productId': res.data['sku'],
                                      'createTime': DateTime.now().millisecondsSinceEpoch
                                    };
                                    ApplePayDBOperate.insertPayHistoryInfo(map);
                                    InAppPay.pay(
                                        PayType.PayType_APPLE,sku: res.data['sku'],orderId: res.data['orderId']);
                                }
                                return;
                                }
                              SmartDialog.show(
                                alignment: Alignment.bottomCenter,
                                clickMaskDismiss: true,
                                maskColor: Color.fromRGBO(0, 0, 0, 0.5), builder: (BuildContext context) {
                                  return ChoosePaymentPage(total: money??0,id: vipType,);
                              },
                              );
                            },
                            child: Container(
                              margin: EdgeInsets.only(top: 50.w),
                              child: Container(
                                height: 90.w,
                                width: 1.sw-60.w,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                    gradient: const LinearGradient(
                                        colors: [Color(0xffEDD0A8),Color(0xffF1BF83)],
                                        begin: Alignment.centerLeft,
                                        end: Alignment.centerRight
                                    ),
                                    borderRadius: BorderRadius.circular(80.w)
                                ),
                                child: Text('确认开通VIP',style: TextStyle(
                                    color: Color(0xff7D532A),
                                    fontWeight: FontWeight.w600,
                                    fontSize: 32.sp
                                ),),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: (){
                        Navigator.of(context).pushNamed('H5Page',arguments: {
                          'url':protocolURL,
                          'title':'《用户协议》'
                        });
                      },
                      child:Image.asset('assets/min/min_vip_bottom.png',width: 1.sw,),
                    ),
                    Container(
                      height: 200,
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
